package com.zs.grain.service

import android.content.Context
import android.util.Log
import com.example.clockkotlin.databaseClockAlarm.AlarmSignal
import java.util.ArrayList
import java.util.Date
import javax.inject.Inject
import javax.inject.Singleton

import com.google.gson.Gson
import org.greenrobot.greendao.query.*
import com.xnkj1688.semplibrary.ulti.*
import com.zs.grain.BuildConfig
import com.xnkj1688.semplibrary.entity.*
import com.xnkj1688.semplibrary.enums.*
import com.zs.grain.tool.clockManage.LocalDataBase
import java.io.File
import java.text.SimpleDateFormat


/**
 * Created by Wesley on 2017/7/15.
 */
@Singleton
class DataService @Inject constructor(
    val mContext: Context,
    val mDaoSession: DaoSession
) {
    var _isFirstStart: Boolean? = null
    val isFirstStart: Boolean
        get() {
            _isFirstStart = if (_isFirstStart == null) true else false
            return _isFirstStart!!
        }

    val isEmulator: Boolean
        get() {
            if (!BuildConfig.DEBUG) return false
            return true;
//            return false
        }

    val isTest: Boolean
        get() {
            if (!BuildConfig.DEBUG) return false
            return false
//            return true;
        }

    val server: String
        get() {
            val setting = getSetting("Server")
//            return setting ?: "10.0.2.2:5188"
//            return setting ?: "47.106.129.241:5188"
            return setting ?: "47.115.54.113:5188"
        }

    var mUpdateComponents: MutableList<Component> = ArrayList()
    var mUpdateAdjustments: MutableList<Adjustment> = ArrayList()
    var currentOrder: Order? = null

    var DaoSetting: SettingDao
    var DaoSystemLog: SystemLogDao
    var DaoMenu: MenuDao
    var DaoGood: GoodDao
    var DaoCategory: CategoryDao
    var DaoReceipe: ReceipeDao
    var DaoComponent: ComponentDao
    var DaoAdjustment: AdjustmentDao
    var DaoIngrident: IngridentDao
    var DaoImage: ImageDao
    var DaoTrack: TrackDao
    var DaoSnapshot: SnapshotDao
    var DaoCash: CashDao
    var DaoCashLog: CashLogDao
    var DaoOrder: OrderDao
    var DaoOrderDetail: OrderDetailDao
    var DaoDeliver: DeliverDao
    var DaoAdvertisement: AdvertisementDao

    val appChannel: String
        get() {
            val setting = getSetting("AppChannel")
            return setting ?: "grain"//BuildConfig.FLAVOR
        }

    val terminalId: Long
        get() {
            val setting = getSetting("TerminalId")
            return if (setting != null) java.lang.Long.parseLong(setting) else 1000
        }

    val verifyCode: String
        get() {
            val setting = getSetting("VerifyCode")
            return setting ?: "123456789"
        }

    val password: String
        get() {
            val setting = getSetting("Password")
            return if (BuildConfig.DEBUG) "" else setting ?: "900100"
        }
	
    val phoneNum:String
        get(){
            val setting = getSetting("PhoneNum")
            return setting ?: "无"
        }

    val deviceType: String
        get() {
            val setting = getSetting("DeviceType")
            return setting ?: "SHJ06X12A"//"Yy"
        }

    val deviceName: String
        get() = getSetting("DeviceName") ?: "/dev/ttyS3"

    val baudrate: Int
        get() {
            val setting = getSetting("Baudrate")
            return if (setting != null) Integer.parseInt(setting) else 19200
        }

    val payWays: String
        get() {
            val setting = getSetting("PayWays")
            return (setting ?: "Face,Alipay,Weixin,Lzf,Icbc").toLowerCase()
        }

    val cardDatas: Map<String, String>
        get() {
            var map = mutableMapOf<String, String>()
            val setting = getSetting("CardNum")
            if (setting != null) {
                for (item in setting.split(';')) {
                    var arr = item.split(':')
                    if (arr.size == 2) map.set(arr[0], arr[1])
                }
            }
            if (map.size<=0)  map.set("######", "1")

            if (setting == null) {
                map.set("######", "1")
                map.set("******", "1")
                return map
            }
            return map;
        }

    val isStop: Boolean
        get() {
            val setting = getSetting("IsStop")
            return if (setting != null) java.lang.Boolean.parseBoolean(setting) else false
        }

    val rotateDegree: Int
        get() = getIntSetting("RotateDegree")

    val adsPath: String
        get() {
            val setting = getSetting("AdsPath")
            return "/data/data/${mContext.packageName}/${setting ?: "ads"}/"
        }

    val imagesPath: String
        get() {
            val setting = getSetting("ImagesPath")
            return "/data/data/${mContext.packageName}/${setting ?: "images"}"
        }

    val craftPath: String
        get() {
            val setting = getSetting("CraftPath")
            return "/data/data/${mContext.packageName}/${setting ?: "crafts"}"
        }

    val craftFileName: String
        get() {
            val setting = getSetting("CraftPath")
            return "/data/data/${mContext.packageName}/${setting ?: "crafts"}"
        }

    val menuSpanCount: Int
        get() {
            val setting = getSetting("MenuSpanCount")
            return setting?.toInt() ?: 4
        }

    val counterCount: Int
        get() {
            val counterCount = getIntSetting("CounterCount")
            return if (counterCount == 0) 1 else counterCount
        }

    var componentTimestamp: Date?
        get() {
            val setting = getSetting("ComponentTimestamp")
            return DateUtil.parse(setting, "yyyy-MM-dd HH:mm:ss.SSS")
        }
        @Synchronized
        set(timestamp) =
            if (timestamp == null)
                this.saveSetting("ComponentTimestamp", null)
            else
                this.saveSetting(
                    "ComponentTimestamp",
                    DateUtil.format(timestamp, "yyyy-MM-dd HH:mm:ss.SSS")
                )

    var adjustmentTimestamp: Date?
        get() {
            val setting = getSetting("AdjustmentTimestamp")
            return DateUtil.parse(setting, "yyyy-MM-dd HH:mm:ss.SSS")
        }
        @Synchronized
        set(timestamp) =
            if (timestamp == null)
                this.saveSetting("AdjustmenttTimestamp", null)
            else
                this.saveSetting(
                    "AdjustmenttTimestamp",
                    DateUtil.format(timestamp, "yyyy-MM-dd HH:mm:ss.SSS")
                )

    var autoRebootTime: Date?
        get() {
            val rt = getSetting("RebootTime")
            return DateUtil.parse(rt, "HH:mm")
        }
        @Synchronized
        set(timestamp) {
            if (timestamp == null)
                this.saveSetting("RebootTime", null)
            else
                this.saveSetting(
                    "RebootTime",
                    DateUtil.format(timestamp, "HH:mm")
                )
        }

    private val mSystemLogLock = Any()

    val menus: List<Menu>
        get() = DaoMenu.loadAll()

    val goods: List<Good>
        get() = DaoGood.loadAll()

    val adjustments: MutableList<Adjustment>
        get() = DaoAdjustment.loadAll()

    val receipes: List<Receipe>
        get() = DaoReceipe.loadAll()

    val components: MutableList<Component>
        get() = DaoComponent.loadAll()

    val tracks: MutableList<Track>
        get() {
            val tracks =
                DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.le(this.counterCount))
                    .list()
            return tracks
        }

    val tracksFromDB: List<Track>
        get() {
            DaoTrack.detachAll()
            val tracks =
                DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.le(this.counterCount))
                    .list()
            return tracks
        }

    val cash: Cash
        get() {
            var cash: Cash? = DaoCash.queryBuilder().limit(1).unique()
            if (cash == null) {
                cash = Cash()
                DaoCash.insert(cash)
            }
            return cash
        }

    val advertisements: MutableList<Advertisement>
        get() = DaoAdvertisement.queryBuilder().build().list()

    fun playingAdsList():MutableList<Advertisement> {//advertisements数据库传进来
        var playingList:MutableList<Advertisement> = ArrayList()
        for (item in advertisements) {
            var file = File(adsPath + item.fileName)
            if (file.exists() ) {
                if(item.enable == true){
                    playingList.add(item)
                }
            }
        }
        return playingList
    }

    val lazyOrders: LazyList<Order>
        get() = DaoOrder.queryBuilder().build().listLazy()

    val lazySnapshots: LazyList<Snapshot>
        get() = DaoSnapshot.queryBuilder().build().listLazy()

    val syncSnapshots: List<Snapshot>
        get() {
            val counterCount = this.counterCount
            for (i in 1..counterCount) {
                var snapshots: LazyList<Snapshot>? = null
                try {
                    val query =
                        DaoSnapshot.queryBuilder().where(SnapshotDao.Properties.CounterNo.eq(i))
                            .build()
                    snapshots = query.listLazy()
                    val list = ArrayList<Snapshot>()
                    for (item in snapshots!!) {
                        list.add(item)
                        if (item.type == SnapshotType.Load.ordinal)
                            return list
                    }
                } finally {
                    snapshots?.close()
                }
            }
            return ArrayList()
        }

    init {
        DaoSetting = mDaoSession.settingDao
        DaoSystemLog = mDaoSession.systemLogDao
        DaoTrack = mDaoSession.trackDao
        DaoMenu = mDaoSession.menuDao
        DaoGood = mDaoSession.goodDao
        DaoReceipe = mDaoSession.receipeDao
        DaoComponent = mDaoSession.componentDao
        DaoAdjustment = mDaoSession.adjustmentDao
        DaoIngrident = mDaoSession.ingridentDao
        DaoCategory = mDaoSession.categoryDao
        DaoSnapshot = mDaoSession.snapshotDao
        DaoImage = mDaoSession.imageDao
        DaoOrder = mDaoSession.orderDao
        DaoOrderDetail = mDaoSession.orderDetailDao
        DaoDeliver = mDaoSession.deliverDao
        DaoCash = mDaoSession.cashDao
        DaoCashLog = mDaoSession.cashLogDao
        DaoAdvertisement = mDaoSession.advertisementDao
        initDatabase()
        if (componentTimestamp != null)
            mUpdateComponents = this.components
        if (adjustmentTimestamp != null)
            mUpdateAdjustments = this.adjustments
    }

    private fun initDatabase() {
        if (DaoGood.loadAll().size <= 0) {
            var good = Good()
            good.id = 0
            good.logoId = 0
            good.name = "苦咖荞麦茶"
            DaoGood.insert(good)
        }
        if (DaoMenu.loadAll().size <= 0) {
            var menu = Menu()
            menu.no = 0;
            menu.name = "雪碧"
            menu.price = 1
            DaoMenu.insert(menu)
            menu = Menu()
            menu.no = 1;
            menu.name = "雪碧"
            menu.price = 1
            DaoMenu.insert(menu)
            menu = Menu()
            menu.no = 2;
            menu.name = "雪碧"
            menu.price = 1
            DaoMenu.insert(menu)
            menu = Menu()
            menu.no = 3;
            menu.name = "雪碧"
            menu.price = 1
            DaoMenu.insert(menu)
            menu = Menu()
            menu.no = 4;
            menu.name = "雪碧"
            menu.price = 1
            DaoMenu.insert(menu)
            menu = Menu()
            menu.no = 5;
            menu.name = "雪碧"
            menu.price = 1
            DaoMenu.insert(menu)
        }
        if (DaoImage.loadAll().size <= 0) {
            var image = Image()
            image.id = 0;
            image.fileName = "xb.png"
            DaoImage.insert(image)
        }
        if (DaoTrack.loadAll().size <= 0) {
            var count = getFloorCount(1) * getFloorTrackCount(1)
            var tracks = ArrayList<Track>()
            for (i in 1..count) {
                var track = Track()
                track.no = i
                track.capacity = 1000
                tracks.add(track);
            }
            tracks[0].goodId = 0
            tracks[0].count = 1000
            DaoTrack.insertInTx(tracks)
        }
    }

    fun getMenus(group: Int): List<Menu> {
        var list = DaoMenu.queryBuilder().where(MenuDao.Properties.Group.eq(group))
            .list()
        return list
    }

    fun getCraftId(goodId: Long): Int {
        var good = DaoGood.queryBuilder().where(GoodDao.Properties.Id.eq(goodId)).unique()
        var craftId = 1000
        try {
            craftId = good.remark.split(";")[0].toInt()
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return craftId
    }

    fun getReceipes(goodId: Long): MutableList<Receipe> {
        var list = DaoReceipe.queryBuilder().where(ReceipeDao.Properties.GoodId.eq(goodId))
            .list()
        return list
    }

    fun getReceipe(id: Long): Receipe? {
        var receipe = DaoReceipe.queryBuilder().where(ReceipeDao.Properties.Id.eq(id)).unique()
        return receipe
    }

    fun getComponents(ingridentId: Int): MutableList<Component> {
        var components =
            DaoComponent.queryBuilder().where(ComponentDao.Properties.IngridentId.eq(ingridentId))
                .list()
        return components
    }

    fun getComponentsIngredient(id:Int):Component{
        val info=
            DaoComponent.queryBuilder().where(ComponentDao.Properties.Id.eq(id)).unique()
        return info;
    }

    fun getIngrident(id: Long): Ingrident? {
        var ingrident =
            DaoIngrident.queryBuilder().where(IngridentDao.Properties.Id.eq(id)).unique()
        return ingrident
    }

    fun getSetting(name: String): String? {
        val setting = DaoSetting.queryBuilder().where(SettingDao.Properties.Name.eq(name)).unique()
        return setting?.value
    }

    fun isLocalDBEnabld(setting: String): Boolean{
        var isEnable = false
        val clocksArray:ArrayList<AlarmSignal> = LocalDataBase.getClocksArray()
        for(ca in clocksArray){
            if(ca.setting.contains(setting)) {
                if(ca.enable) {
                    isEnable=true
                    break
                }
                else isEnable = false
            }
        }
        return isEnable
    }

    fun getFromLocalDatabase(setting:String,type:String): String?{
        var settingTime:String ?= null
        val clocksArray:ArrayList<AlarmSignal> = LocalDataBase.getClocksArray()
        for(ca in clocksArray){
            if(ca.setting.contains(setting)) {
                if(setting.contains("vol"))
                    settingTime = ca.time + " " + ca.setting//.substring(0,4)+((ca.setting.substring(5).toInt()+1)*6).toString()
                else {
                    if(type=="setting")
                        settingTime = ca.setting.substring(8)
                    else settingTime = ca.time
                }
            }
        }
        return settingTime
    }

    fun saveSetting(name: String, value: String?) {
        var setting: Setting? =
            DaoSetting.queryBuilder().where(SettingDao.Properties.Name.eq(name)).unique()
        if (setting == null) {
            setting = Setting()
            setting.name = name
            setting.value = value
            this.DaoSetting.insert(setting)
        } else {
            setting.value = value
            this.DaoSetting.update(setting)
        }
    }

    fun getIntSetting(name: String): Int {
        val value = this.getSetting(name)
        return if (value == null) 0 else Integer.valueOf(value)
    }

    fun getFloorCount(counterNo: Int): Int {
        val floorCount = getIntSetting("FloorCount" + counterNo.toString())
        return if (floorCount == 0) 6 else floorCount
    }

    fun getFloorTrackCount(counterNo: Int): Int {
        val floorTrackCount = getIntSetting("FloorTrackCount" + counterNo.toString())
        return if (floorTrackCount == 0) 9 else floorTrackCount
    }

    fun insertLog(content: String, level: Int) {
        val log = SystemLog()
        log.content = content
        log.level = level
        var id = java.lang.Long.parseLong(DateUtil.formatCurrentDate("yyMMddHHmmssSSS"))
        synchronized(mSystemLogLock) {
            while (DaoSystemLog.load(id) != null) id++
            val nowTime = Date(System.currentTimeMillis())
            val sdFormatter = SimpleDateFormat("yyyy-MM-dd")
            log.timestamp = nowTime
            log.id = id
            this.DaoSystemLog.insert(log)
        }
    }

    fun insertLog(content: String) {
        this.insertLog(content, Log.INFO)
    }

    fun getMenu(menuNo: Long?): Menu? {
        return if (menuNo == null) null else DaoMenu.load(menuNo)
    }

    fun getGood(id: Long): Good? {
        return DaoGood.load(id)
    }

    fun getGoods(categoryId: Long): List<Good> {
        val goods = ArrayList<Good>()
        val menus = menus
        for (m in menus) {
            val good = DaoGood.load(m.goodId)
            if (good != null && good.categoryId == categoryId) goods.add(good)
        }
        return goods
    }

    fun getGoodCount(id: Long): Int {
        var count = 0
        val tracks = this.getTracks(id)
        for (item in tracks) {
            if (item.state == TrackState.Ready.ordinal || item.state == TrackState.None.ordinal)
                count += item.count
        }
        return count
    }

    fun getImage(id: Long): Image? {
        return DaoImage.load(id)
    }

    fun getTracks(counterNo: Int): List<Track> {
        val tracks =
            DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.eq(counterNo)).list()
        return tracks
    }

    fun getTracksFromDB(counterNo: Int): List<Track> {
        DaoTrack.detachAll()
        val tracks =
            DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.eq(counterNo)).list()
        return tracks
    }

    fun getTracksFromDB(counterNo: Long): List<Track> {
        DaoTrack.detachAll()
        val tracks =
            DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.eq(counterNo)).list()
        return tracks
    }

    fun getTracks(goodId: Long): List<Track> {
        return DaoTrack.queryBuilder().where(
            TrackDao.Properties.CounterNo.le(this.counterCount),
            TrackDao.Properties.GoodId.eq(goodId),
            TrackDao.Properties.State.notEq(TrackState.Idle.ordinal)
        ).list()
    }

    fun getTrack(goodId: Long): Track? {
        var qb: QueryBuilder<*> = DaoTrack.queryBuilder()
        val counter = this.counterCount
        val count = 0
        qb = qb.where(
            TrackDao.Properties.CounterNo.le(counter),
            TrackDao.Properties.GoodId.eq(goodId),
            TrackDao.Properties.Count.gt(count)
        )
        val track = qb.whereOr(
            TrackDao.Properties.State.eq(TrackState.Ready.ordinal),
            TrackDao.Properties.State.eq(TrackState.None.ordinal)
        ).orderDesc(TrackDao.Properties.Count).limit(1).unique()
        return if (track == null) null else track as Track
    }

    fun update(component: Component) {
        this.DaoComponent.update(component)
        if (!mUpdateComponents.contains(component))
            mUpdateComponents.add(component)
        this.componentTimestamp = Date()
    }

    fun update(components: List<Component>) {
        this.DaoComponent.updateInTx(components)
        for (item in components) {
            if (!mUpdateComponents.contains(item))
                mUpdateComponents.add(item)
        }
        this.componentTimestamp = Date()
    }

    fun insertTracks(tracks: List<Track>) {
        this.DaoTrack.insertInTx(tracks)
    }

    fun insertTracks(vararg tracks: Track) {
        this.DaoTrack.insertInTx(*tracks)
    }

    fun getTrack(counterNo: Int, no: Int): Track {
        var qb: QueryBuilder<*> = DaoTrack.queryBuilder()
        qb = qb.where(
            TrackDao.Properties.CounterNo.eq(counterNo),
            TrackDao.Properties.No.eq(no)
        )
        val track = qb.limit(1).unique() as Track
        return track
    }

    fun deleteAllTracks() {
        this.DaoTrack.deleteAll()
        this.DaoTrack.detachAll()
    }

    fun getSnapshots(counterNo: Int): List<Snapshot> {
        val snapshots =
            DaoSnapshot.queryBuilder().where(SnapshotDao.Properties.CounterNo.eq(counterNo)).list()
        for (item in snapshots) {
            val tracks =
                DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.eq(item.id)).list()
            item.tracks = tracks
        }
        return snapshots
    }

    fun getSnapshots(counterNo: Long, count: Int): List<Snapshot> {
        val snapshots =
            DaoSnapshot.queryBuilder().where(SnapshotDao.Properties.CounterNo.eq(counterNo))
                .limit(count).list()
        for (item in snapshots) {
            val tracks =
                DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.eq(item.id)).list()
            item.tracks = tracks
        }
        return snapshots
    }

    fun getLastSnapshot(counterNo: Long): Snapshot? {
        return DaoSnapshot.queryBuilder().where(SnapshotDao.Properties.CounterNo.eq(counterNo))
            .orderDesc(SnapshotDao.Properties.Id).limit(1).unique()
    }

    fun insert(snapshot: Snapshot) {
        this.DaoSnapshot.insert(snapshot)
        this.DaoTrack.insertInTx(snapshot.tracks)
    }

    fun delete(snapshot: Snapshot) {
        val tracks =
            DaoTrack.queryBuilder().where(TrackDao.Properties.CounterNo.eq(snapshot.id)).list()
        DaoTrack.deleteInTx(tracks)
        DaoSnapshot.delete(snapshot)
    }

    fun deleteSnapshots(snapshots: Iterable<Snapshot>) {
        for (item in snapshots) {
            this.delete(item)
        }
        this.DaoSnapshot.detachAll()
    }

    fun update(cash: Cash) {
        DaoCash.update(cash)
    }

    fun getCashLogs(count: Int): List<CashLog> {
        return DaoCashLog.queryBuilder().limit(count).list()
    }

    fun getSystemLogs(count: Int): List<SystemLog> {
        return DaoSystemLog.queryBuilder().orderDesc(SystemLogDao.Properties.Timestamp).limit(count).list()
    }

    fun insert(log: CashLog) {
        DaoCashLog.insert(log)
    }

    fun delete(log: CashLog) {
        DaoCashLog.delete(log)
    }

    fun getUnsyncSystemLogs(count: Int): List<SystemLog> {
        return DaoSystemLog.queryBuilder().where(SystemLogDao.Properties.IsUploaded.isNull)
            .limit(count).list()
    }

    fun deleteCashLogs(logs: Iterable<CashLog>) {
        DaoCashLog.deleteInTx(logs)
        DaoCashLog.detachAll()
    }

    fun deleteSystemLogs(logs: Iterable<SystemLog>) {
        DaoSystemLog.deleteInTx(logs)
        DaoSystemLog.detachAll()
    }

    fun insert(order: Order) {
        this.DaoOrder.insert(order)
        this.DaoOrderDetail.insertInTx(order.details)
    }

    fun insert(components: List<Component>) {
        this.DaoComponent.insertInTx(components)
    }

    fun save(order: Order) {
        if (this.DaoOrder.load(order.id) == null) this.DaoOrder.insert(order)
        else this.DaoOrder.update(order)

        for (d in order.details) {
            d.orderId = order.id
            var detail = this.DaoOrderDetail.queryBuilder().where(
                OrderDetailDao.Properties.OrderId.eq(d.orderId),
                OrderDetailDao.Properties.No.eq(d.no)
            ).unique()
            if (detail == null) this.DaoOrderDetail.insert(d)
            else this.DaoOrderDetail.update(d)
        }
    }

    fun save(adjustment: Adjustment) {
        val ads =
            DaoAdjustment.queryBuilder().where(
                AdjustmentDao.Properties.ComponentId.eq(adjustment.componentId),
                AdjustmentDao.Properties.AdjustmentId.eq(adjustment.adjustmentId)
            ).list()
        if (ads == null || ads.size <= 0) {
            adjustment.id = null
            this.DaoAdjustment.insert(adjustment)
        } else {
            adjustment.id = ads[0].id
            this.DaoAdjustment.update(adjustment)
        }
    }

    fun getOrder(orderId: Long): Order? {
        val order = this.DaoOrder.load(orderId)
        if (order != null && order.details.size <= 0) {
            val details =
                DaoOrderDetail.queryBuilder().where(OrderDetailDao.Properties.OrderId.eq(order.id))
                    .list()
            order.details.addAll(details)
        }
        if (order != null && order.delivers.size <= 0) {
            val delivers =
                DaoDeliver.queryBuilder().where(DeliverDao.Properties.OrderId.eq(order.id)).list()
            order.delivers.addAll(delivers)
        }
        return order
    }

    fun update(order: Order) {
        Log.d(TAG, Gson().toJson(order))
        this.DaoOrder.update(order)
        this.DaoOrderDetail.updateInTx(order.details)
        if (order.isSuccess == null) return

        val delivers = this.getDelivers(order.id)
        order.delivers.addAll(delivers)
    }

    fun delete(order: Order) {
        DaoOrderDetail.deleteInTx(order.details)
        DaoDeliver.deleteInTx(order.delivers)
        DaoOrder.delete(order)
        this.DaoOrderDetail.detachAll()
        this.DaoDeliver.detachAll()
        this.DaoOrder.detachAll()
    }

    fun getDelivers(orderId: Long): List<Deliver> {
        return DaoDeliver.queryBuilder().where(DeliverDao.Properties.OrderId.eq(orderId)).list()
    }

    fun getDelivers(orderId: Long, orderDetailNo: Int): List<Deliver> {
        return DaoDeliver.queryBuilder().where(
            DeliverDao.Properties.OrderId.eq(orderId),
            DeliverDao.Properties.OrderDetailNo.eq(orderDetailNo)
        ).list()
    }

    companion object {
        val TAG = "DataService"
    }
}
